<?php
/**
* @myIPN for Sobi 2
* @Copyright (C) 2007 Ethan Chai Voon Chong, http://www.ethansoft.com
* @All Rights Reserved
*/

defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

if (file_exists("components/com_myipn/lang/".$GLOBALS['mosConfig_lang'].".php")) {
	include_once("components/com_myipn/lang/".$GLOBALS['mosConfig_lang'].".php");
} else {
	include_once("components/com_myipn/lang/english.php");
}

require_once ( $mainframe->getPath( 'front_html' ) );
require_once ( $mainframe->getPath( 'class' ) );

$task = mosGetParam( $_REQUEST, 'task', 'display');
$item = mosGetParam( $_REQUEST, 'item', '');

// load the configuration
$myipn_config = new mosMyipnConfig( $database );
$myipn_config->load( 1 );

switch($task) {
	case "paypal":
		process_paypal();
		break;
	case "complete":
		HTML_Myipn::display_complete();
		break;
	case "cancel":
		HTML_Myipn::display_cancel();
		break;
	default:
		break;
}


function getTimeAndDate($days = null) {
        global $mosConfig_offset;
        if($days)
                return date( 'Y-m-d H:i:s', time() + ($days * 24 * 60 * 60) + ($mosConfig_offset * 60 * 60));
        else
                return date( 'Y-m-d H:i:s', time() + $mosConfig_offset * 60 * 60  );
    }

function process_paypal() {
	global $database, $myipn_config;

$output = "";

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

$posts = "";
foreach ($_POST as $key => $value) {
	$posts .= "$key => $value\r\n";
	$value = urlencode(stripslashes($value));
	$req .= "&$key=$value";
}

// assign posted variables to local variables
$username = $_POST['custom'];
$payer_email = $_POST['payer_email'];
$receiver_email = $_POST['receiver_email'];
$entry_number = $_POST['item_number'];
$entry_name = $_POST['item_name'];
$txn_id = $_POST['txn_id'];
$subscr_id = $_POST['subscr_id'];
$subscr_date = $_POST['subscr_date'];
$txn_type = $_POST['txn_type'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$payment_status = $_POST['payment_status'];
$period3 = $_POST['period3'];
$mc_amount3 = $_POST['mc_amount3'];
$residence_country = $_POST['residence_country'];
$test_ipn = $_POST['test_ipn'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$name = $first_name.$last_name;

$header = "";
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
if ($test_ipn==1) {
	$fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30);
} else {
	$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
}

if (!$fp) {
	// HTTP ERROR
} else {
	fputs ($fp, $header . $req);
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0) {

			// check the payment_status is Completed
			if($txn_type == "subscr_payment"){
			if ($payment_status != "Completed") {
				$output .= "Payment status: $payment_status\r\n";
			}
			

			// check that txn_id has not been previously processed
			$query = "SELECT id FROM #__myipn_sub_paypal_log WHERE txn_id='$txn_id' AND txn_id !=''";
                        $database->setQuery($query);
			$row2 = null;
			
			if ( $database->loadObject($row2) )
			{
				$output .= "Previously processed txn_id: $txn_id\r\n";	
			}
			
			// Start grab paypal email from sobi 2
			$query = "SELECT configValue FROM #__sobi2_config WHERE configKey='payPalMail' AND sobi2Section='payment'";
                        $database->setQuery($query);

                        $row =null;

                        if ($database->loadObject($row)) {
                              $primary_email = $row->configValue;
                        }
			//End grab paypal email from sobi 2
			
			// Start check on reciever email and configured email
			if ($receiver_email != $primary_email) {
				$output .= "Not Primary PayPal email: $receiver_email\r\n";
			}
			// End check on reciever email and configured email
			
			// check that payment_amount/payment_currency are correct with sobi entry 
			$query = "SELECT * FROM #__sobi2_config WHERE configValue='$payment_currency' AND configKey='currency'";
                        $database->setQuery($query);
                        $row2 = null;

                        if ( !$database->loadObject($row2) )
                        {
                                $output .= "Currency Mismatch \r\n";
                        }
			}
			
			
			// Start get the catid for the entry
                        $query = "SELECT catid FROM #__sobi2_cat_items_relations WHERE itemid='$entry_number'";
                        $database->setQuery($query);

                        $row =null;

                        if ($database->loadObject($row)) {
                              $entry_cat = $row->catid;
                        }
			// End get catid for sobi entry

			// Saving Paypal Transaction log
                        $query = "INSERT INTO #__myipn_sub_paypal_log VALUES ( '','$username','$payer_email','$receiver_email','$entry_cat','$entry_number','$entry_name','$txn_id','$txn_type','$subscr_id','$subscr_date','$payment_amount','$payment_currency','$payment_status','$period3','$mc_amount3','$residence_country','$test_ipn')";
                        $database->setQuery($query);
                        $database->query();

			// Keep Processed if everything alright
			if ($output=="") {
				if($txn_type == "subscr_payment"){
				if ($test_ipn==1) {
					$output .= $posts;
					$output .= "\r\n";
					save_log($output);
				}

				// process the payment

					$query = "SELECT itemid FROM #__sobi2_item WHERE itemid='$entry_number'";
					$database->setQuery($query);

					$row2 = null;
					
					$query = "SELECT configValue FROM #__sobi2_config WHERE configKey='entryExpirationTime' AND sobi2Section='general'";
                                                $database->setQuery($query);

                                        $row =null;

                                        if ($database->loadObject($row))
					{
					     $entryExpirationTime = $row->configValue + 1; 
					}
					
					if ( $database->loadObject($row2) ) {
						
						$publish_down = getTimeAndDate($entryExpirationTime);

						// Update the exact sobi entry 
						$query = "UPDATE #__sobi2_item SET
                                                                published = '1', approved='1', publish_down='$publish_down'
                                                                WHERE itemid = '$entry_number'";
						$database->setQuery($query);
						$database->query();

						//save_log($query);
						automail($name, $username, $payer_email);
						
					} else {
						// fail Paypal transaction Check					
					}
				}

			} else {
				// log for manual investigation
				save_log($output);
			}

		} else if (strcmp ($res, "INVALID") == 0) {
			$output = "INVALID return\r\n".$posts;
			// log for manual investigation
			save_log($output);
		}
	}
	fclose ($fp);
}

}

function save_log($output) {
	global $sandbox;
	$filename = "components/com_myipn/log.txt";
	if ($sandbox) {
		$fd = fopen($filename,"w");
	} else {
		$fd = fopen($filename,"a");
	}
	$output .= "\r\n";
	fwrite($fd, $output);
	fclose ($fd);
}

function automail($name, $username, $email) {
	global $myipn_config;

	$from = $GLOBALS['mosConfig_mailfrom']; //$myipn_config->paypal_email;
	$fromname = $GLOBALS['mosConfig_fromname'];
	$subject = $GLOBALS['mosConfig_fromname'] . ': ' . _MYIPN_EMAIL_SUBJECT;
	$text = sprintf( _MYIPN_AUTO_MAIL, $name, $username, $GLOBALS['mosConfig_sitename'], $GLOBALS['mosConfig_live_site'] );

	mosMail( $from, $fromname, $email, $subject, $text );
}

?>
